﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using PetShop.Web.Entities;
using PetShop.Web.WebComponents;

namespace PetShop.Web
{
    public partial class WebFormSignIn : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void SubmitClicked(object sender, ImageClickEventArgs e)
        {
            if (Page.IsValid)
            {
                string userId = CleanString.InputText(txtUserId.Text, 50);
                string password = CleanString.InputText(txtPassword.Text, 50);


                if (string.IsNullOrEmpty(userId))
                    throw new ArgumentException("userId");
                if (string.IsNullOrEmpty(password))
                    throw new ArgumentException("password");

                AccountInfo myAccountInfo = null;

                string sql = "SELECT Email," +
                             "FirstName, LastName, Addr1, " +
                             " Addr2, City, State, Zip, " +
                             " Country, Phone, " +
                             " LangPref, FavCategory, MyListOpt, " +
                             " BannerOpt " +
                             " FROM Account " +
                             " WHERE UserId = @UserId AND Password = @Password";


                using (var cmd = new SqlCommand())
                {
                    using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
                    {
                        cmd.Connection = conn;
                        cmd.CommandText = sql;
                        cmd.CommandType = CommandType.Text;
                        var parm = new SqlParameter("@UserId", SqlDbType.VarChar, 80);
                        parm.Value = userId;
                        cmd.Parameters.Add(parm);
                        parm = new SqlParameter("@Password", SqlDbType.VarChar, 80);
                        parm.Value = password;
                        cmd.Parameters.Add(parm);
                        conn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            if (rdr.Read())
                            {
                                var myAddress = new AddressInfo(rdr.GetString(1), rdr.GetString(2), rdr.GetString(3),
                                                                rdr.GetString(4), rdr.GetString(5), rdr.GetString(6),
                                                                rdr.GetString(7), rdr.GetString(8), rdr.GetString(9));
                                myAccountInfo = new AccountInfo(userId, password, rdr.GetString(0), myAddress,
                                                                rdr.GetString(10), rdr.GetString(11),
                                                                Convert.ToBoolean(rdr.GetInt32(12)),
                                                                Convert.ToBoolean(rdr.GetInt32(13)));
                            }
                        }
                    }
                }


                if (myAccountInfo != null)
                {
                    HttpContext.Current.Session["ACCOUNT_KEY"] = myAccountInfo;


                    if (FormsAuthentication.GetRedirectUrl(userId, false).EndsWith("default.aspx"))
                    {
                        FormsAuthentication.SetAuthCookie(userId, false);
                        HttpContext.Current.Response.Redirect("MyAccount.aspx?action=signIn", true);
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(userId, false);
                        HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userId, false), true);
                    }
                    valUserId.IsValid = true;
                }
                else
                {
                    valUserId.ErrorMessage = "Sign in failed! Please try again.";
                    valUserId.IsValid = false;
                }
            }
        }
    }
}